package de.bk.timecalc.core;

/**
 * Represents a duration.
 * 
 * Test: {@link DurationTest}
 * 
 * @author Bastian Krol
 * @version $Revision:$ $Date:$ $Author:$
 */
public class Duration
{
  private int millisecondsSum;

  private int minutes;
  private int seconds;
  private int millis;

  /**
   * Creates a duration with the given amount of milliseconds. This class is
   * only intended for durations of a few minutes. If milliseconds is larger
   * than {@link Integer#MAX_VALUE}, it will be capped to
   * {@link Integer#MAX_VALUE}. Thus the maximum duration that can be stored is
   * 35791 minutes, 23 seconds and 647 milliseconds.
   * 
   * @param milliseconds
   */
  public Duration(long milliseconds)
  {
    if (milliseconds < 0)
    {
      throw new IllegalArgumentException("Not allowed: " + milliseconds
          + " milliseconds");
    }
    if (milliseconds > Integer.MAX_VALUE)
    {
      milliseconds = Integer.MAX_VALUE;
    }
    this.millisecondsSum = (int) milliseconds;

    this.minutes = this.millisecondsSum / 60000;
    this.seconds = (this.millisecondsSum % 60000) / 1000;
    this.millis = (this.millisecondsSum % 1000);
  }

  final int getMillisecondsSum()
  {
    return this.millisecondsSum;
  }

  final int getMinutes()
  {
    return this.minutes;
  }

  final int getSeconds()
  {
    return this.seconds;
  }

  final int getMillis()
  {
    return this.millis;
  }

  /**
   * {@inheritDoc}
   * 
   * @see java.lang.Object#toString()
   */
  @Override
  public String toString()
  {
    StringBuffer stringBuffer = new StringBuffer();
    if (this.minutes > 0)
    {
      stringBuffer.append(this.minutes);
      stringBuffer.append(":");
    }
    if (this.seconds < 10)
    {
      stringBuffer.append("0");
    }
    stringBuffer.append(this.seconds);
    stringBuffer.append(":");
    if (this.millis < 10)
    {
      stringBuffer.append("00");
    }
    else if (this.millis < 100)
    {
      stringBuffer.append("0");
    }
    stringBuffer.append(this.millis);
    return stringBuffer.toString();
  }
}
